import smtplib
import random
from email.message import EmailMessage
import re

def is_valid_email(email):
    """验证邮箱地址格式"""
    pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
    return re.match(pattern, email) is not None

def generate_code():
    return str(random.randint(1000, 9999))

def send_verification_code(email, code):
    """发送验证邮件"""
    # 验证邮箱格式
    if not is_valid_email(email):
        print("邮箱格式错误")
        return False
    
    # 邮箱配置
    sender_email = "1518965403@qq.com"
    sender_password = "danbuaiuvdohgdff"
    smtp_server = "smtp.qq.com"
    smtp_port = 465
    
    # 创建邮件内容
    msg = EmailMessage()
    msg['From'] = sender_email
    msg['To'] = email
    msg['Subject'] = "验证码 - 李庄白肉"
    msg.set_content(f"""
    您好！
    
    您正在重置密码，验证码是: {code}
    
    此验证码10分钟内有效，请勿泄露给他人。
    
    如果不是您本人操作，请忽略此邮件。
    
    李庄白肉
    """)
    
    try:
        # 连接 SMTP 服务器并发送邮件
        with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
            server.login(sender_email, sender_password)
            server.send_message(msg)
            print(f"验证码已发送至: {email}")
            return True
    except Exception as e:
        print(f"发送邮件失败: {str(e)}")
        return False